﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Eneta.Portal.Controls;
using Microsoft.SharePoint;
using Eneta.Portal.Common.Repository;
using Eneta.Portal.Common.Dto;
using Eneta.Portal.Common.Helpers;
using Eneta.Portal.Common;

namespace Eneta.Portal.Literature.Controls
{
    public class MagazineDetailView : UserControl
    {

        protected Literal MagazineTitle;
        protected HtmlAnchor AuthorProfileLink;
        protected HtmlImage AuthorImage;
        protected HtmlGenericControl AuthorName;
        protected Literal EntryDate;
        protected Literal EntryDescription;
        protected HtmlImage MagazinePicture;
        protected HtmlAnchor MagazinePictureUrl;
        protected Literal MagazinePageTitle;
        protected Literal MagazinePublisher;
        protected Literal MagazinePublishingYear;
        protected HtmlAnchor additionalInfoUrl;
        protected TagsViewControl LiteratureTags;
        protected TagsSelectionControl LiteratureTagsSelection;
        protected ModerationControl LiteratureModeration;
        protected LiteratureCommentsViewControl LiteratureCommentsListing;
        protected LiteratureCommentAddControl LiteratureAddComment;
        protected Label MessageLabel;
        protected HtmlGenericControl MessageBox;
        protected Repeater addLinksRepeater;
        protected HtmlAnchor addLiteratureLink;
        protected PlaceHolder profilenav;

        public bool ShowPendingitems { get; set; }
        public string LiteratureLink { get; set; }
        public string LiteratureLinkText { get; set; }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            addLinksRepeater.ItemDataBound += new RepeaterItemEventHandler(addLinksRepeater_ItemDataBound);
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            try
            {
                var item = SPContext.Current.ListItem;
                if (item == null)
                {
                    Logger.LogInfo("Current Magazine is null", "BookDetailView_OnLoad");
                    return;
                }
                var repository = new LiteratureRepository(SPContext.Current.Web);
                var dto = repository.GetLiteratureItemById(item.ID);
                if (dto.Status == SPModerationStatusType.Approved)
                {
                    LoadViewData(dto);
                }
                else
                {
                    LiteratureAddComment.Visible = false;
                    if (SPContext.Current.Web.CurrentUser != null)
                    {
                        if (SPContext.Current.Web.CurrentUser.IsSiteAdmin || (ShowPendingitems && dto.AuthorId == SPContext.Current.Web.CurrentUser.ID))
                            LoadViewData(dto);
                        else
                        {
                            Logger.LogInfo("Kasutaja ei ole administraator ega autor, suuname ümber.", "MagazineDetailView_OnLoad");
                            Response.Redirect("/oppimine/ajakirjad", false);
                            return;
                        }
                    }
                }
                if (SPContext.Current.Web.CurrentUser != null)
                {
                    BindLinks();
                    profilenav.Visible = true;
                }

            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
            }
        }

        public static string GetPromoBox(HttpContext context)
        {
            var user = SPContext.Current.Web.CurrentUser;
            if (user == null)
            {
                var output =
                    @"<p><a href='/_layouts/Eneta.Portal.Authentication/LiveAuthHandler.aspx?action=login'>Logi sisse</a> ja lisa oma arvamus!</p>
					<p>Eneta portaali saad kasutada oma Live ID kontoga - see on sama, millega 
					suhtled Messengeris. Logi sisse, sest Enetas saad lisaks kommenteerimisele 
					<a href='/kommuun/eneta/Lehed/liikmed.aspx'>teha palju muud põnevat</a>.</p>";
                return output;
            }

            var rep = new UserProfileRepository(SPContext.Current.Web);
            var profile = rep.GetUserProfileByUserName(user.LoginName);
            if (profile == null)
                return string.Empty;

            var output2 = "<p>{0}, lisa sinagi üks <a href='/oppimine/ajakirjad/edit.aspx'>huvitav ajakiri</a> Eneta portaali!</p>";
            output2 = string.Format(output2, profile.UserName);
            return output2;
        }

        void addLinksRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            var item = e.Item.DataItem as UrlDto;
            if (item == null)
                return;
            var link = e.Item.FindControl("LinksControl") as HtmlAnchor;
            if (link == null)
                return;
            link.HRef = item.Url;
            link.InnerText = item.LinkName;
        }

        private void BindLinks()
        {
            addLiteratureLink.InnerText = LiteratureLinkText;
            addLiteratureLink.HRef = LiteratureLink;

            var urls = new List<UrlDto>();
            if (LiteratureLink == "/oppimine/ajakirjad/edit.aspx")
            {
                urls.Add(new UrlDto() { Url = "/oppimine/raamatud/edit.aspx", LinkName = Resources.Literature.AddBook });
            }
            else
            {
                urls.Add(new UrlDto() { Url = "/oppimine/ajakiri/edit.aspx", LinkName = Resources.Literature.AddMagazine });
            }
            urls.Add(new UrlDto() { Url = "/uudised/teated/addannouncement.aspx", LinkName = Resources.Literature.AddAnnouncement });
            urls.Add(new UrlDto() { Url = "/addblog.aspx", LinkName = Resources.Literature.AddBlog });
            urls.Add(new UrlDto() { Url = "/firmad/edit.aspx", LinkName = Resources.Literature.AddCompany });
            this.addLinksRepeater.DataSource = urls;
            this.addLinksRepeater.DataBind();
        }

        private void LoadViewData(LiteratureDto dto)
        {
            if (dto.PosterProfileId != 0)
            {
                UserProfileRepository repository = new UserProfileRepository(SPContext.Current.Site.RootWeb);
                var user = repository.GetUserProfileById(dto.PosterProfileId);
                if (user != null)
                {
                    AuthorProfileLink.HRef = UrlHelper.GetProfileUrl(dto.PosterProfileId);
                    AuthorProfileLink.Title = user.UserName;
                    AuthorImage.Src = user.UserImage32x32Url;
                    AuthorImage.Alt = user.UserName;
                    AuthorImage.Visible = true;
                    if (SPContext.Current.Web.CurrentUser != null)
                    {
                        if (SPContext.Current.Web.CurrentUser.LoginName.EndsWith(user.LiveIdToken))
                        {
                            AuthorName.InnerText = Resources.Literature.YouLabel;
                            AuthorProfileLink.Title = Resources.Literature.YourProfileLabel;
                        }
                        else
                        {
                            AuthorName.InnerText = user.UserName;
                        }
                    }
                    else
                    {
                        AuthorName.InnerText = user.UserName;
                    }
                    if (Request.UrlReferrer != null)
                    {
                        if (Request.UrlReferrer.ToString().Contains("/oppimine/ajakirjad/edit.aspx") && Request.QueryString["msg"] == "magazineedit")
                        {
                            MessageBox.Style.Remove("display");
                            MessageLabel.Text = Resources.Literature.MagazineSaved;
                        }
                        else if (Request.UrlReferrer.ToString().Contains("/oppimine/ajakirjad/edit.aspx") && Request.QueryString["msg"] == "magazinesave")
                        {
                            MessageBox.Style.Remove("display");
                            MessageLabel.Text = Resources.Literature.MagazineSavedWaitingApproval;
                        }
                    }
                }
            }
            if (!string.IsNullOrEmpty(dto.Title))
            {
                MagazineTitle.Text = dto.Title;
            }
            EntryDate.Text = dto.PostedDate.ToShortDateString();

            if (!string.IsNullOrEmpty(dto.Summary))
            {
                EntryDescription.Text = dto.Summary;
            }
            if (!string.IsNullOrEmpty(dto.LiteratureImageUrl))
            {
                SPFile file = SPContext.Current.Site.RootWeb.GetFile(dto.LiteratureImageUrl);
                if (file.Exists)
                {
                    MagazinePicture.Alt = dto.Title;
                    MagazinePicture.Src = dto.LiteratureImageUrl;
                    MagazinePicture.Visible = true;
                }
            }
            if (!string.IsNullOrEmpty(dto.Title))
            {
                MagazinePageTitle.Text = dto.Title;
            }
            if (!string.IsNullOrEmpty(dto.Author))
            {
                MagazinePublisher.Text = dto.BookAuthors;
            }
            if (!string.IsNullOrEmpty(dto.PublishingYear))
            {
                MagazinePublishingYear.Text = dto.PublishingYear.Replace("|", " " + Resources.Literature.TimesLabel+ " ");
            }
            if (!string.IsNullOrEmpty(dto.AdditionalInfoURL))
            {
                MagazinePictureUrl.HRef = dto.AdditionalInfoURL;
                MagazinePictureUrl.Title = dto.Title;
                additionalInfoUrl.HRef = dto.AdditionalInfoURL;
                additionalInfoUrl.InnerText = Resources.Literature.OpenInNewWindowLabel;
                additionalInfoUrl.Title = dto.AdditionalInfoURL;
                additionalInfoUrl.Visible = true;
            }
            else
            {
                MagazinePictureUrl.Visible = false;
                additionalInfoUrl.Visible = false;
            }
            if (dto.Keywords != null)
            {
                LiteratureTags.Keywords = dto.Keywords;
            }
            Logger.LogInfo("Ajakirja detailvaate ID: " + dto.ID, GetType().ToString());
            LiteratureTagsSelection.ItemId = dto.ID;
            if (SPContext.Current.Web.CurrentUser == null)
                LiteratureModeration.Visible = false;
            LiteratureModeration.ItemId = dto.ID;
            LiteratureAddComment.ItemId = dto.ID;
            LiteratureCommentsListing.ItemId = dto.ID;
        }
    }
}
